package com.wrx.club_management_backend.utils;

import ch.qos.logback.classic.layout.TTLLLayout;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.wrx.club_management_backend.dto.UserDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Map;
import java.util.concurrent.TimeUnit;
import static com.wrx.club_management_backend.utils.RedisConstant.LOGIN_USER_KEY;
import static com.wrx.club_management_backend.utils.RedisConstant.LOGIN_USER_KEY_TTL;

/**
 * 登录状态续约
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public  RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }


    /**
     * 拦截一切请求，如果请求带有 authorization 就对 token 进行刷新
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 从请求头中获取 token
        String token = request.getHeader("Authorization");
        if(StrUtil.isBlank(token)){
            UserHolder.removeUser();
            return true;
        }
        //2. 如果当前请求有 token 的话， 就可以从redis中查找userdto
        Map<Object, Object> map = stringRedisTemplate.opsForHash().entries(LOGIN_USER_KEY + token);
        UserDTO dto = BeanUtil.fillBeanWithMap(map, new UserDTO(), false);
        UserHolder.saveUser(dto);
        //3. 最后对该key进行续约
        stringRedisTemplate.expire(LOGIN_USER_KEY + token, LOGIN_USER_KEY_TTL, TimeUnit.MINUTES);
        return true;

    }
}
